"use strict";
var koa = require('koa.io');
//实例化app
var app = koa();

//配置body parser
var path = require('path');
var koaBody = require('koa-body');
app.use(koaBody({ multipart: true, formidable: { uploadDir: path.join(__dirname, './upload') } }));//指定上传位置,允许上传

//配置session
var session = require('koa-session');
app.keys = ['En Taro Tassadar', 'En Taro Adun', 'My Life For Aiur'];
app.use(session(app));

//配置jade引擎
var Jade = require('koa-jade')
var jade = new Jade({
    viewPath: './views',
    debug: false,
    pretty: true,
    noCache: true
});
app.use(jade.middleware);
//配置static file
var path = require('path');
var staticCache = require('koa-static-cache')
var files = {}
app.use(staticCache(path.join(__dirname, './public'), {
    maxAge: 365 * 24 * 60 * 60
}, files));
staticCache(path.join(__dirname, './bower_components'), {
    maxAge: 365 * 24 * 60 * 60
}, files);




//预备挂上我们的串口服务
var PipeController = require('./service/PipeController.js');
var pipeCtrl = new PipeController();
app.use(function* (next) {
    this.state.pipeCtrl = pipeCtrl;
    yield next;
});

app.io.use(function* userLeft(next) {
    // on connect
    console.log('user connected');
    pipeCtrl.socketHelper.addSocket(this);
    yield* next;
    // on disconnect
});

//注册页面路由
var router = require('koa-router')();
var registerRoutes = require('./routes');
registerRoutes(router);
app.use(router.routes());



//默认路径
app.use(function* () {
    this.redirect('/home');
});

//生成数据库
var models = require('./models');
models.sequelize.sync().then(function () {
    console.log('网站启动在3000端口');
    app.listen(3000);
});